<?php
namespace Mobile\Controller;
use Think\Controller;
use \Mobile\Model\xcx;

class XCXapiController extends Controller{

    public function getSessionKey(){
    	$sid = I('shopId');
        $xcx =  new xcx($sid);

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' .$xcx->appid. '&secret=' .$xcx->secret. '&js_code='.$_GET['code']. '&grant_type=authorization_code';
//echo $url;
        $data = file_get_contents($url);
//var_dump($data);
        $sessionId = $xcx->createNoncestr();

        //把数据缓存下来，作为session
        $data = json_decode($data,true);

        if(empty($data['openid'])){
            die('获取openid失败');
        }

        $U = M('User');
        $user = $U->field('user_id')->where('s_id='.$sid.' AND openid="'.$data['openid'].'"')->find();
        if(!$user){
            $add = array(
                'openid' => $data['openid'],
                's_id' => $sid,
                'register_time' => time()
            );
            $id = $U->add($add);
            //存储userId
            $data['user_id'] = $id;
        }else{
            $data['user_id'] = $user['user_id'];
        }

        S($sessionId,$data);

        $data['sessionId'] = $sessionId;

        echo json_encode($data);

    }

    public function  userInfo(){
        $sessionId = I('sessionId');
        $data = S($sessionId);

        if(empty($data['openid'])){
            die;
        }
        $U = M('User');
        $user = $U->where('user_id='.$data['user_id'])->find();
        if(!$user['nick_name']){
            $save = array(
                'nick_name' => $_GET['nickName'],
                'avatar_url' => $_GET['avatarUrl'],
            );
            $U->where('user_id='.$data['user_id'])->save($save);
            $user['nick_name'] = $_GET['nickName'];
            $user['avatar_url'] = $_GET['avatarUrl'];
        }
        echo json_encode($user);
    }

    public function test(){
    	$goods = M('goods')->where('s_id=12 or s_id=17')->select();
    	$O = M('goods_spec_option');

    	foreach ($goods as $key => $value) {
    		$op = $O->where('goods_id='.$value['goods_id'])->find();
    		if(!$op){
    			$save = array(
    				'c_id' => $value['c_id'],
    				's_id' => $value['s_id'],
    				'goods_id' => $value['goods_id'],
    				'option_title' => '',
    				'price' => $value['price'],
    				'market_price' => $value['price'],
    				'stock' => 999,
    				'specs' => 0,
    				'checked' => 0,
    				 );
    			$O->add($save);
    		}
    	}
    }


    public function pay(){

        $sessionId= I('sessionId');

        $userName= I('userName');

        $telNumber= I('telNumber');

        $address= I('address');

        $goods = I('goods');

        $shopId = I('shopId');

        $fid = I('fid');

        $couponId = I('couponId');

        $latitude = I('latitude');

        $longitude = I('longitude');

        $get_time = I('get_time');

        $tableNumber = I('tableNumber');

        $xcx =  new xcx($shopId);

        //计算金额

        $goodsInfo = $xcx->countMoney($goods,$couponId);

        $total_fee = $goodsInfo['money'];

        //从缓存里获取openid

        $session = S($sessionId);

        $openid = $session['openid'];

        //订单号

        $number = $xcx->createNoncestr(5).date('YmdHi');

        //缓存prepay_id ，用于回调时发送模板消息

        S('prepay_id'.$number,$fid);

        $body = "外卖订购";

        //下单
        $return = $xcx->pay($openid,$body,$total_fee * 100,$number);

        //添加订单
        $add  = array(

            'order_number' => $number,

            'user_id' => $session['user_id'],

            'pay_time' => time(),

            'pay_status' => 1,

            'pay_money' => $total_fee,

            'time' => time(),

            'order_status' => 1,

        );

        $add1  = array(

            'order_number' => $number,

            'user_name' => $userName,

            'mobile' => $telNumber,

            'shop_id' => $shopId,

            'address' => $address,

            'cart' =>  $goodsInfo['cart'],

            'user_id' => $session['user_id'],

            'price' => $total_fee,

            'time' => time(),

            'coupon_id' => $couponId,

            'latitude' => $latitude,

            'longitude' => $longitude,

            'get_time' => $get_time,

            'table_number' => $tableNumber,

        );

        M('order')->add($add);

        M('order_detail')->add($add1);

        echo json_encode($return);

    }

    //重新支付功能
    public function againPay(){

        $sessionId= I('sessionId');

        $orderId= I('orderId');

        $order = M('order_detail')->field('cart,order_number,price,coupon_id,shop_id')->find($orderId);

        //重新生成订单号
        $xcx =  new \Mobile\Model\xcx($order['shop_id']);

        $number = $xcx->createNoncestr(5).date('YmdHi');

        M('order')->where('order_number="'.$order['order_number'].'"')->save(array('order_number'=>$number));

        M('order_detail')->where('id='.$orderId)->save(array('order_number'=>$number));

        //缓存prepay_id ，用于回调时发送模板消息
        S('prepay_id'.$number,$fid);

        $total_fee = floatval($order['price'] * 100);

        //从缓存里获取openid
        $session = S($sessionId);
        $openid = $session['openid'];

        $body = "外卖订购";

        //下单
        $return = $xcx->pay($openid,$body,$total_fee,$number);

        //用掉优惠券
        // if($order['coupon_id']){
        //     M('coupon')->where('id='.$order['coupon_id'])->save(array('status'=>1));
        // }

        echo json_encode($return);

    }

    public function notify(){

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($postObj === false) {
            die('parse xml error');
        }

        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }

        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
		echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        $arr = (array)$postObj;

        //锁
        $lock = S('lock'.$arr['out_trade_no']);
        if($lock){
        	die();
        }else{
        	S($arr['out_trade_no'],1,3600);
        }

        file_put_contents('./data/notify'.date('Ymd').'.txt', var_export($arr,true)."\r\n",FILE_APPEND);

        unset($arr['sign']);

        $order_detail = M('order_detail')->where(array('order_number'=>$arr['out_trade_no']))->find();

        $xcx =  new xcx($order_detail['shop_id']);

        $sign = $xcx->getSign($arr);

        if ($sign == $postObj->sign) {
            //更改订单状态
            $save = array(

                'pay_status' => 2,

                'pay_time' =>$arr['time_end'],

                'other_order_number'=>$arr['transaction_id'],

                'order_status'=>2,

            );
            M('order')->where(array('order_number'=>$arr['out_trade_no']))->save($save);

            //增加销量
            $xcx->addSales($order_detail['cart']);
            //发送模板消息
            $form_id = S('prepay_id'.$arr['out_trade_no']);
           	$xcx->sendTemplateMsg($form_id,$order_detail,$arr['openid']);

            return $postObj;
        }

    }





    /**

     * 给微信用户公众号消息

     * @param string $openId 微信openID

     * @param int $content 发送的内容

     * @return url

     */

    public function sendWxMassage($content){

        // $wx = A('Home/Wx');

        // $wxInfo = $wx->wxcode(0);

        // $open_id = $wxInfo['openid'] ;

    }

    //客服功能
    public function kf(){

        $xcx =  new \Mobile\Model\xcx();

        $xcx->msg();

    }



}

